package cn.tedu.tmall.front.content.handler;

import cn.tedu.tmall.common.web.JsonResult;
import cn.tedu.tmall.common.ServiceCodeEnum;
import cn.tedu.tmall.common.ex.ServiceException;
import io.swagger.v3.oas.annotations.Hidden;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@Hidden
@RestControllerAdvice
public class GlobeExceptionHandler {
    @ExceptionHandler(ServiceException.class)
    public JsonResult HandleRunningTimeException(ServiceException e) {
        log.debug("捕获运行时异常",e);
        return JsonResult.fail(ServiceCodeEnum.ERROR.getCode(),e.getMessage());
    }
    @ExceptionHandler(RuntimeException.class)
    public JsonResult HandleRunningTimeException(RuntimeException e) {
        log.debug("捕获运行时异常",e);
        return JsonResult.fail(ServiceCodeEnum.ERROR.getCode(),e.getMessage());
    }

    @ExceptionHandler
    public JsonResult HandlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuffer stringBuffer  = new StringBuffer();
       for(FieldError fieldError : fieldErrors) {
           String defaultMessage = fieldError.getDefaultMessage();
           stringBuffer.append(defaultMessage);
           stringBuffer.append(",");
       }
        String msg = deleteLastChar(stringBuffer);
        return JsonResult.fail(ServiceCodeEnum.ERROR.getCode(),msg);
    }
    private String deleteLastChar(StringBuffer str) {
        // 处理null或空字符串
        if (str == null || str.length() == 0) {
            return "";
        }

        String string = str.toString();
        // 查找最后一个逗号的位置
        int lastCommaIndex = string.lastIndexOf(",");
        System.out.println(lastCommaIndex);
        System.out.println(string.length());
        // 若没有逗号，直接返回原字符串；否则截取到最后一个逗号前
        if (lastCommaIndex == -1) {
            return string;
        } else {
            return string.substring(0, lastCommaIndex);
        }
    }


    @ExceptionHandler
    public JsonResult handleException(Throwable e) {
        log.error("系统出现异常:{}",e.getMessage());
        return JsonResult.fail(ServiceCodeEnum.ERROR.getCode(),"网络波动,请稍后再试");
    }
}
